package cn.com.dashihui.web.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;

import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Brand;
import cn.com.dashihui.web.service.BrandService;

@RequiresAuthentication
public class BrandController extends BaseController{
	private static final Logger logger = Logger.getLogger(BrandController.class);
	private BrandService service = new BrandService();

	@RequiresPermissions("dict:brand:index")
    public void index(){
        render("index.jsp");
    }

	public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPage(pageNum, pageSize));
	}

	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：名称为空
	 */
	public void doAdd(){
		//品牌名
		String name = getPara("name");
		if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else{
			//保存
			if(service.addBrand(new Brand()
				.set("name", name))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}

	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：名称为空
	 */
	public void doEdit(){
		//品牌ID
		String brandid = getPara("brandid");
		//品牌名
		String name = getPara("name");
		if(StrKit.isBlank(brandid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else{
			//更新
			if(service.editBrand(new Brand()
				.set("id", brandid)
				.set("name", name))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&service.delBrand(id)){
			logger.info("删除品牌【"+id+"】");
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
